package web.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.Execution;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
import org.springframework.web.servlet.view.RedirectView;

import web.domain.Leave;
import web.domain.User;
import web.domain.UserTask;

import com.njry.util.ActivitiHelper;
import com.njry.util.DBHelper;
import org.xml.sax.SAXParseException;

public class ProcessInstanceController extends MultiActionController{
	private final static SimpleDateFormat dateformat14 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	private ActivitiHelper activitiHelper;
	public DBHelper dBHelper;// 
	public DBHelper getDBHelper() {
		return dBHelper;
	}

	public void setDBHelper(DBHelper helper) {
		dBHelper = helper;
	}

	/**
	 * 获取流程定义
	 * @return
	 */
	public List<ProcessDefinition> activitiList(HttpServletRequest request,
			HttpServletResponse response){
		List<ProcessDefinition> procDefList = activitiHelper.activitiListByprocesskey("process1");
		return procDefList;
	}
	
	/**
	 * 获取流程实例流程实例
	 * @return
	 */
	public List<ProcessInstance> listProcInst(HttpServletRequest request,
			HttpServletResponse response){
		String pdfid = request.getParameter("pdfid");
		pdfid="process1";
		List<ProcessInstance> procInstList = activitiHelper.listProcInstByPdfid(pdfid);
		return procInstList;
	}
	
	/**
	 * 删除流程定义
	 * @param request
	 * @param response
	 * @return
	 */
	public ModelAndView deleteProcessDefinitionsAction(HttpServletRequest request,
			HttpServletResponse response){
		String deploymentId=request.getParameter("deploymentId");
		activitiHelper.repositoryService.deleteDeployment(deploymentId, true);
		return new ModelAndView(new RedirectView("activeManager.do?doMethod=getProcessDefinitionsAction"));
	}
	
	/**
	 * 获取流程定义
	 * @param request
	 * @param response
	 * @return
	 */
	public ModelAndView getProcessDefinitionsAction(HttpServletRequest request,
			HttpServletResponse response){
		Map model=new HashMap();
		List<ProcessDefinition> procDefList = activitiList(request,response);
		request.setAttribute("processDefinitions", procDefList);
		return new ModelAndView("adminList");
	}
	
	/**
	 * 审核操作
	 * @param request
	 * @param response
	 * @return
	 */
	public ModelAndView operateLeaveAction(HttpServletRequest request,
			HttpServletResponse response){
		Map model=new HashMap();
		String taskId=request.getParameter("taskId");
		String operate=request.getParameter("operate");
		User user = (User) request.getSession().getAttribute("userSession");
		if(user.getUser_id().endsWith("2")){//如果是经理审批
			String key=(String) activitiHelper.getTaskService().getVariable(taskId, "leave_id");
			System.out.println("key:"+key);
			Map objMap=dBHelper.queryForMap("select * from leave_ where leave_id='"+key+"'");
			System.out.println("objMap:"+objMap);
			Map<String, Object> variables = new HashMap<String, Object>();
			
			if(operate.endsWith("1")&&Integer.valueOf((String) objMap.get("totleday"))<3){
				variables.put("operate", "1");
				variables.put("totalday", Integer.valueOf((String) objMap.get("totleday")));
				dBHelper.update("update leave_ set status ='经理通过' where leave_id='"+key+"'");
			}if(operate.endsWith("1")&&Integer.valueOf((String) objMap.get("totleday"))>=3){
				variables.put("totalday", Integer.valueOf((String) objMap.get("totleday")));
				variables.put("operate", "1");
				dBHelper.update("update leave_ set status ='老板审批中' where leave_id='"+key+"'");
			}else if(operate.endsWith("0")){
				variables.put("totalday", Integer.valueOf((String) objMap.get("totleday")));
				variables.put("operate", "0");
				dBHelper.update("update leave_ set status ='经理不通过' where leave_id='"+key+"'");
			}
			activitiHelper.getTaskService().setVariables(taskId, variables);
			activitiHelper.getTaskService().complete(taskId);
			
			List list=dBHelper.queryForList("select * from leave_ where user_id='2'");
			model.put("list", list);
			//获取待办请假单
			List<Task> tasks = activitiHelper.taskService.createTaskQuery().taskAssignee(user.getUser_id()).orderByTaskCreateTime().desc().list();
			
			List <UserTask> usertasks=new ArrayList<UserTask>();
			for(Task task : tasks){
//				activitiHelper.taskService.complete(task.getId(), variables);//

				String id="";
				UserTask userTask=new UserTask();
				userTask.setTaskName(task.getName());
				userTask.setTaskID(task.getId());
				userTask.setTaskCreateTime(dateformat14.format(task.getCreateTime()));
				userTask.setTaskDescription(task.getDescription());
				userTask.setId(id);
				usertasks.add(userTask);
			}
			model.put("usertasks", usertasks);
			return new ModelAndView("leaveForm/jinglileaveList",model);
		}else if(user.getUser_id().endsWith("3")){//如果是老板审批
			String key=(String) activitiHelper.getTaskService().getVariable(taskId, "leave_id");
			System.out.println("key:"+key);
			Map objMap=dBHelper.queryForMap("select * from leave_ where leave_id='"+key+"'");
			System.out.println("objMap:"+objMap);
			Map<String, Object> variables = new HashMap<String, Object>();
			
			if(operate.endsWith("1")){
				variables.put("operate", "1");
				dBHelper.update("update leave_ set status ='老板通过' where leave_id='"+key+"'");
			}else if(operate.endsWith("0")){
				variables.put("operate", "0");
				dBHelper.update("update leave_ set status ='老板不通过' where leave_id='"+key+"'");
			}
			
			activitiHelper.getTaskService().setVariables(taskId, variables);
			activitiHelper.getTaskService().complete(taskId);
			
			List<Task> tasks = activitiHelper.taskService.createTaskQuery().taskAssignee(user.getUser_id()).orderByTaskCreateTime().desc().list();
			List <UserTask> usertasks=new ArrayList<UserTask>();
			for(Task task : tasks){
				String id="";
				UserTask userTask=new UserTask();
				userTask.setTaskName(task.getName());
				userTask.setTaskID(task.getId());
				userTask.setTaskCreateTime(dateformat14.format(task.getCreateTime()));
				userTask.setTaskDescription(task.getDescription());
				
				userTask.setId(id);
				usertasks.add(userTask);
			}
			model.put("usertasks", usertasks);
			return new ModelAndView("leaveForm/laobanleaveList",model);
		}
		
		return new ModelAndView("adminList");
	}
	
	/**
	 * 
	 * @return
	 */
	public String listExecution(HttpServletRequest request,
			HttpServletResponse response) {
		String processInstanceId = request.getParameter("procInstId");
		List<Execution> exectionList = activitiHelper.listExecutionByProId(processInstanceId);
		request.setAttribute("exectionList", exectionList);
		return "listExecution";
	}
	
	/**
	 * 
	 * @return
	 */
	public ModelAndView deployProcDef(HttpServletRequest request,
			HttpServletResponse response){
		Deployment deploy = activitiHelper.deployProcDefByPath("web/processfile/leave.bpmn20.xml");
		return new ModelAndView(new RedirectView("activeManager.do?doMethod=getProcessDefinitionsAction"));
	}
	
	/**
	 * 保存
	 * @return
	 */
	public ModelAndView saveLeave(HttpServletRequest request,
			HttpServletResponse response){
		User user = (User) request.getSession().getAttribute("userSession");
		Leave leave = new Leave();
		String day=request.getParameter("day");
		String content=request.getParameter("content");
		int t=dBHelper.update("insert into leave_ values('"+java.util.UUID.randomUUID().toString()+"','"+user.getUser_id()+"'" +
				",'"+day+"','"+dateformat14.format(new Date())+"','新建','"+content+"') ");
		List list=dBHelper.queryForList("select * from leave_ where user_id='"+user.getUser_id()+"'");
		request.setAttribute("list", list);
		
		if(user.getUser_id().endsWith("1")){
			return new ModelAndView("leaveForm/yuangongleaveList");
		}if(user.getUser_id().endsWith("2")){
			return new ModelAndView("leaveForm/jinglileaveList");
		}if(user.getUser_id().endsWith("3")){
			return new ModelAndView("leaveForm/laobanleaveList");
		}
		return null;
	}
	
	/**
	 * 登陆首页
	 * @return
	 */
	public ModelAndView indexLeaveAction(HttpServletRequest request,
			HttpServletResponse response){
		Map model=new HashMap();
		User user = (User) request.getSession().getAttribute("userSession");
		if(user.getUser_id().equals("1")){
			List list=dBHelper.queryForList("select * from leave_ where user_id='1'");
			for(int i=0;i<list.size();i++){
				System.out.println(list.get(i));
			}
			model.put("list", list);
			return new ModelAndView("leaveForm/yuangongleaveList",model);
		}else if(user.getUser_id().equals("2")){
			List list=dBHelper.queryForList("select * from leave_ where user_id='2'");
			for(int i=0;i<list.size();i++){
				System.out.println(list.get(i));
			}
			model.put("list", list);
			//获取待办请假单
			List<Task> tasks = activitiHelper.taskService.createTaskQuery().taskAssignee(user.getUser_id()).orderByTaskCreateTime().desc().list();
			
			List <UserTask> usertasks=new ArrayList<UserTask>();
			for(Task task : tasks){
//				activitiHelper.taskService.complete(task.getId(), variables);//

				String id="";
				UserTask userTask=new UserTask();
				userTask.setTaskName(task.getName());
				userTask.setTaskID(task.getId());
				userTask.setTaskCreateTime(dateformat14.format(task.getCreateTime()));
				userTask.setTaskDescription(task.getDescription());
				
				userTask.setId(id);
				usertasks.add(userTask);
			}
			model.put("usertasks", usertasks);
			return new ModelAndView("leaveForm/jinglileaveList",model);
		}else if(user.getUser_id().equals("3")){
			List<Task> tasks = activitiHelper.taskService.createTaskQuery().taskAssignee(user.getUser_id()).orderByTaskCreateTime().desc().list();
			List <UserTask> usertasks=new ArrayList<UserTask>();
			for(Task task : tasks){
				String id="";
				UserTask userTask=new UserTask();
				userTask.setTaskName(task.getName());
				userTask.setTaskID(task.getId());
				userTask.setTaskCreateTime(dateformat14.format(task.getCreateTime()));
				userTask.setTaskDescription(task.getDescription());
				
				userTask.setId(id);
				usertasks.add(userTask);
			}
			model.put("usertasks", usertasks);
			return new ModelAndView("leaveForm/laobanleaveList",model);
		}
		return new ModelAndView("leaveForm/yuangongleaveList",model);
	}
	
	/**
	 * 删除
	 * @return
	 */
	public ModelAndView deleteLeave(HttpServletRequest request,
			HttpServletResponse response){
		Map model=new HashMap();
		User user = (User) request.getSession().getAttribute("userSession");
		dBHelper.update("delete from leave_ where leave_id='"+request.getParameter("leave_id")+"'");
		List list=dBHelper.queryForList("select * from leave_ where user_id='"+user.getUser_id()+"'");
		model.put("list", list);
		return new ModelAndView(new RedirectView("activeManager.do?doMethod=indexLeaveAction"),model);
	}
	
	/**
	 * 提交任务
	 * @return
	 */
	public ModelAndView applyLeaveAction(HttpServletRequest request,
			HttpServletResponse response){
		User user = (User) request.getSession().getAttribute("userSession");
		String leave_id=request.getParameter("leave_id");
		 Map<String, Object> variables = new HashMap<String, Object>();
		 variables.put("user", user);
		 variables.put("leave_id", leave_id);
		 ProcessInstance pi = activitiHelper.getRuntimeService().startProcessInstanceByKey("process1",leave_id, variables);
		 if(user.getUser_id().equals("1")){
			 dBHelper.update("update leave_ set status ='经理审批中' where leave_id='"+leave_id+"'");
		 }
		 if(user.getUser_id().equals("2")){
			 dBHelper.update("update leave_ set status ='老板审批中' where leave_id='"+leave_id+"'");
		 }
		return new ModelAndView(new RedirectView("activeManager.do?doMethod=indexLeaveAction"));
	}
	
	/**
	 * 删除流程实例
	 * @return
	 */
	public String deleteProcDef(HttpServletRequest request,
			HttpServletResponse response){
		activitiHelper.deleteProcDefByprocesskey("process_leave");
	    return "activitiList";
	}


	public ActivitiHelper getActivitiHelper() {
		return activitiHelper;
	}

	public void setActivitiHelper(ActivitiHelper activitiHelper) {
		this.activitiHelper = activitiHelper;
	}
	public String getOperatorId(HttpServletRequest request) {
		User user = (User) request.getSession().getAttribute("scopedTarget.user");
        return  user.getUser_id();
	}

}
